package com.conversationboard.filter.compression;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class CompressionServletResponseWrapper extends HttpServletResponseWrapper {

    private HttpServletResponse originalResponse = null;
    private ServletOutputStream stream = null;
    private PrintWriter writer = null;
    private int minimumToCompress = 0;


    public CompressionServletResponseWrapper(HttpServletResponse response) {
        super(response);
        originalResponse = response;
    }


    public ServletOutputStream createOutputStream() throws IOException {
        CompressionResponseStream stream = new CompressionResponseStream(originalResponse);
        stream.setBuffer(minimumToCompress);

        return stream;

    }


    public void finishResponse() throws IOException {
        if (writer != null) {
            writer.close();
        } else {
            if (stream != null) {
                stream.close();
            }
        }
    }


    public void flushBuffer() throws IOException {
        CompressionResponseStream compressionStream = (CompressionResponseStream) stream;
        compressionStream.flush();
    }


    public ServletOutputStream getOutputStream() throws IOException {

        if (this.writer != null) {
            throw new IllegalStateException("getWriter() has already been called.");
        }

        if (this.stream == null) {
            this.stream = createOutputStream();
        }

        return (this.stream);

    }


    public PrintWriter getWriter() throws IOException {

        if (this.writer != null) {
            return (this.writer);
        }
        
        if (stream != null) {
            throw new IllegalStateException("getOutputStream() has already been called for this response");
        }

        this.stream = createOutputStream();

        String characterEncoding = originalResponse.getCharacterEncoding();

        if (characterEncoding != null) {
            this.writer = new PrintWriter(new OutputStreamWriter(this.stream, characterEncoding));
        } else {
            this.writer = new PrintWriter(this.stream);
        }

        return this.writer;

    }


    public void setMinimumToCompress(int minimumToCompress) {
        this.minimumToCompress = minimumToCompress;
    }


    public void setContentType(String contentType) {
        originalResponse.setContentType(contentType);
    }

}
